// search.js
var shihan = require('../../common/fetch')
var config = require('../../common/config')
var app = getApp()
var that
var range
var winScale = 750 / app.data.deviceInfo.windowWidth
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    res_navbar: ['商品', '店铺'],
    searchGoods: [], // 搜索结果
    searchBrandList: [], // 搜索结果
    searchKeyword: "", // 搜索关键词
    searchResultShow: false, // 是否显示搜索结果
    filterConflag: false, //筛选内容隐藏
    sort: '',
    start: 1,
    count: 10,
    startprice: '',
    endprice: '',
    brandids: '',
    cids: '',
    totalflag: "active",
    salesflag: "",
    priceflag: "",
    priceimg: "",
    filterimg: "",
    promotion_type: '',
    showLoading: false,
    defaults: 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png',
    prohasMore: true
  },
  /**https://img-oss.shihanbainian.com/shihan2/icon/small_routine/paixu_icon.png
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this
    var pages = getCurrentPages();
    if (pages.length >= 2) {
      var prevPage = pages[pages.length - 2];
      prevPage.setData({
        promotefresh: false
      })
    }
    var searchHistorys = wx.getStorageSync('searchHistorysKey') || []; // 历史浏览记录 从本地缓存中获取前10条数据
    var res = wx.getSystemInfoSync()
    that.gethotword()
    if (searchHistorys.length > 0) {
      that.setData({
        searchHistorys: searchHistorys.length >= 10 ? searchHistorys.slice(0, 10) : searchHistorys,
        winHeight: res.windowHeight,
        winWidth: res.windowWidth
      });
    } else {
      that.setData({
        searchHistorys: searchHistorys
      });
    }
    this.setData({
      winHeight: res.windowHeight
    })
    range = 660 / (750 / that.data.winWidth)
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
    if (options.tag) {
      this.historylabel(options.tag)
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    that.setData({
      searchHistorys: wx.getStorageSync('searchHistorysKey') || [],
    });
  },

  // 滚动计算滚动条距离
  onScroll: function (ev) {
    var scrollTop = ev.detail.scrollTop;
    if (scrollTop > (288 / winScale)) {
      this.setData({
        tabopacity: 'block'
      });
    } else {
      this.setData({
        tabopacity: 'none'
      });
    }
    if (scrollTop > 200) {
      this.setData({
        backToTop: true
      });
    } else {
      this.setData({
        backToTop: false
      });
    }
  },
  onBackToTop: function () {
    this.setData({
      backToTop: false,
      scrollTop: 0
    })
  },
  onScrolla: function (ev) {
    var scrollTopa = ev.detail.scrollTop;
    if (scrollTopa > 200) {
      this.setData({
        backToTopa: true
      });
    } else {
      this.setData({
        backToTopa: false
      });
    }
  },
  onBackToTopa: function () {
    this.setData({
      backToTopa: false,
      scrollTopa: 0
    })
  },
  lowerprice: function (ev) {
    this.setData({
      startprice: ev.detail.value
    })
  },
  upperprice: function (ev) {
    this.setData({
      endprice: ev.detail.value
    })
  },
  closeSearch: function () { //返回上一级
    wx.navigateBack({})
  },
  deletehistory: function () { //清除搜索记录
    wx.removeStorageSync('searchHistorysKey')
    that.setData({
      searchHistorys: []
    });
  },
  // 搜索确认搜索
  onSearchConfirm: function (ev) {
    var searchKeyword = ev.detail.value;
    this.historylabel(searchKeyword)
  },
  remove: function (arr, item) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] != item) {
        result.push(arr[i]);
      }
    }
    return result;
  },
  historylabel: function (param) {
    var searchHistorys = that.data.searchHistorys;
    that.setData({
      showLoading: true,
      searchKeyword: param
    });
    if (param.trim()) {
      that.setData({
        totalflag: "active",
        salesflag: "",
        priceflag: "",
        priceimg: '',
        sort: '',
        start: 1,
        showLoading: true,
        searchGoods: [],
        searchResultShow: true
      });
      this.filterlabel()
      this.filterconfirm()
      // 添加搜索历史记录
      if (searchHistorys.length > 0) {
        searchHistorys = this.remove(searchHistorys, param);
      }
      if (searchHistorys.length == 0) {
        searchHistorys.push(param);
      } else {
        searchHistorys.unshift(param);
      }
      wx.setStorage({
        key: "searchHistorysKey",
        data: searchHistorys,
        success: function () {
          that.setData({
            searchHistorys: searchHistorys
          });
        }
      });
    } else {
      if (this.data.hotsearchword) {
        that.setData({
          showLoading: true,
          searchKeyword: this.data.hotsearchword,
          searchResultShow: true
        });
        this.filterlabel()
        this.filterconfirm()
        // 添加搜索历史记录
        if (searchHistorys.length > 0) {
          searchHistorys = this.remove(searchHistorys, this.data.hotsearchword);
        }
        if (searchHistorys.length == 0) {
          searchHistorys.push(this.data.hotsearchword);
        } else {
          searchHistorys.unshift(this.data.hotsearchword);
        }
        wx.setStorage({
          key: "searchHistorysKey",
          data: searchHistorys,
          success: function () {
            that.setData({
              searchHistorys: searchHistorys
            });
          }
        });
      }
    }
  },
  searchByhistag: function (e) {
    this.setData({
      searchKeyword: e.currentTarget.dataset.keyword
    })
    this.historylabel(this.data.searchKeyword)
  },
  searchByTag: function (e) {
    var adverttype = e.currentTarget.dataset.type;
    if (adverttype) {
      wx.navigateTo({
        url: '/pages/strategyinfo/strategyinfo?url=' + encodeURIComponent(e.currentTarget.dataset.type)
      })
    } else {
      this.setData({
        searchKeyword: e.currentTarget.dataset.keyword
      })
      this.historylabel(this.data.searchKeyword)
    }
  },
  gethotword: function () { //hot_search_word
    var that = this
    shihan.sendRequest(config.hot_search_word, 'GET', {}, {})
      .then(function (response) {
        that.setData({
          hotTag: response.data.data,
          hotsearchword: config.sh_search_keyword
        })
      }, function (error) {
        console.log(error);
      });
  },
  onResNavbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.index
    });
  },
  toggle: function () { //价格
    that.setData({
      totalflag: "",
      salesflag: "",
      priceflag: "active",
      start: 1,
      showLoading: true,
      searchGoods: []
    })
    if (!that.data.priceimg) {
      that.setData({
        priceimg: "top",
        sort: 'price_asc'
      })
    } else if (that.data.priceimg == "top") {
      that.setData({
        priceimg: "down",
        sort: 'price_desc'
      })
    } else {
      that.setData({
        priceimg: "top",
        sort: 'price_asc'
      })
    }
    this.filterconfirm(this.data.brandids, this.data.cids, this.data.attributes, this.data.startprice, this.data.endprice)
  },
  changetotal: function () { //综合
    that.setData({
      totalflag: "active",
      salesflag: "",
      priceflag: "",
      priceimg: '',
      sort: '',
      start: 1,
      showLoading: true,
      searchGoods: []
    })
    this.filterconfirm(this.data.brandids, this.data.cids, this.data.attributes, this.data.startprice, this.data.endprice)
  },
  changesales: function () { //销量
    that.setData({
      totalflag: "",
      salesflag: "active",
      priceflag: "",
      priceimg: '',
      sort: 'hot',
      start: 1,
      showLoading: true,
      searchGoods: []
    })
    this.filterconfirm(this.data.brandids, this.data.cids, this.data.attributes, this.data.startprice, this.data.endprice)
  },
  changefliter: function () {
    this.animation.translateX(-range).step();
    that.setData({
      stopScroll: true,
      filterConflag: true,
      animationData: this.animation.export()
    })
  },
  searchbrand: function (a) {
    shihan.sendRequest(config.searchbrand, 'GET', {
      kw: a
    }, {})
      .then(function (response) {
        that.setData({
          searchBrandList: response.data.data,
          searchResultShow: true
        });
      }, function (error) {
        console.log(error);
      });
  },
  viewgoodsDetail: function (e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id
    })
  },
  openstoredetail: function (e) {
    wx.navigateTo({
      url: '/pages/storedetail/storedetail?id=' + e.currentTarget.dataset.id + '&type=' + e.currentTarget.dataset.type
    })
  },
  selectfilter: function (e) {
    // console.log(e)
    var that = this
    var big = e.currentTarget.dataset.a
    var small = e.currentTarget.dataset.b
    var flitername = e.currentTarget.dataset.flitername
    var vname = e.currentTarget.dataset.vname

    if (big >= 0 && small >= 0) {
      var activeitem = that.data.searchGoodsList.sh_attributes[big].sh_options[small]
      if (activeitem.active == '') {
        activeitem.active = 'active';
      } else {
        activeitem.active = '';
      }
    }
    if (big >= 0 && small == undefined) {
      var activeitem = that.data.searchGoodsList
      if (activeitem[vname][big].active == '') {
        activeitem[vname][big].active = 'active';
      } else {
        activeitem[vname][big].active = '';
      }
    }

    this.setData({
      searchGoodsList: that.data.searchGoodsList
    })
    // console.log(that.data)
  },
  otherclosefilter: function () {
    this.animation.translateX(range).step();
    this.setData({
      filterConflag: false,
      stopScroll: false,
      animationData: this.animation.export()
    })
  },
  closefilter: function () {
    var bigarr = this.data.searchGoodsList
    var arra = {};
    var arrb = [];
    var arrc = [];
    var arrd = [];
    var arre = [];
    for (var i = 0; i < bigarr.sh_attributes.length; i++) {
      for (var j = 0; j < bigarr.sh_attributes[i].sh_options.length; j++) {
        if (bigarr.sh_attributes[i].sh_options[j].active == 'active') {
          arrb.push(bigarr.sh_attributes[i].sh_options[j].sh_value);
          arra[bigarr.sh_attributes[i].sh_attribute_id] = arrb.join()
        }
      }
      arrb.length = 0;
    }
    for (var k = 0; k < bigarr.sh_brands.length; k++) {
      if (bigarr.sh_brands[k].active == 'active') {
        arrc.push(bigarr.sh_brands[k].sh_id)
      }
    }
    for (var l = 0; l < bigarr.sh_categorys.length; l++) {
      if (bigarr.sh_categorys[l].active == 'active') {
        arrd.push(bigarr.sh_categorys[l].sh_cid)
      }
    }
    for (var m = 0; m < bigarr.sh_promotions.length; m++) {
      if (bigarr.sh_promotions[m].active == 'active') {
        arre.push(bigarr.sh_promotions[m].sh_promotion_type)
      }
    }
    this.animation.translateX(range).step();
    this.setData({
      brandids: arrc.join(','),
      cids: arrd.join(','),
      attributes: arra,
      promotion_type: arre.join(','),
      filterConflag: false,
      stopScroll: false,
      start: 1,
      searchGoods: [],
      animationData: this.animation.export()
    })
    if (this.data.brandids || this.data.cids || this.data.promotion_type || this.data.startprice || this.data.endprice) {
      this.setData({
        showLoading: true,
        filterflag: 'active'
      })
    } else {
      this.setData({
        showLoading: true,
        filterflag: ''
      })
    }
    this.filterconfirm(this.data.brandids, this.data.cids, this.data.attributes, this.data.startprice, this.data.endprice)
  },
  addactive: function (param) {
    for (var i = 0; i < param.sh_attributes.length; i++) {
      for (var j = 0; j < param.sh_attributes[i].sh_options.length; j++) {
        param.sh_attributes[i].sh_options[j].active = ''
        param.sh_attributes[i].foldflag = false
      }
    }
    for (var k = 0; k < param.sh_brands.length; k++) {
      param.sh_brands[k].active = ''
      param.sh_brands[0].foldflag = false
    }
    for (var l = 0; l < param.sh_categorys.length; l++) { //
      param.sh_categorys[l].active = ''
      param.sh_categorys[0].foldflag = false
    }
    for (var m = 0; m < param.sh_promotions.length; m++) { //
      param.sh_promotions[m].active = ''
      param.sh_promotions[0].foldflag = false
    }
  },
  dropsorting: function (e) {
    var type = e.currentTarget.dataset.type
    if (type == 'brands') {
      if (this.data.searchGoodsList.sh_brands[0].foldflag == false) {
        this.data.searchGoodsList.sh_brands[0].foldflag = true
      } else {
        this.data.searchGoodsList.sh_brands[0].foldflag = false
      }
    } else if (type == 'categorys') {
      if (this.data.searchGoodsList.sh_categorys[0].foldflag == false) {
        this.data.searchGoodsList.sh_categorys[0].foldflag = true
      } else {
        this.data.searchGoodsList.sh_categorys[0].foldflag = false
      }
    } else if (type == 'attributes') {
      var index = e.currentTarget.dataset.index
      if (this.data.searchGoodsList.sh_attributes[index].foldflag == false) {
        this.data.searchGoodsList.sh_attributes[index].foldflag = true
      } else {
        this.data.searchGoodsList.sh_attributes[index].foldflag = false
      }
    }
    this.setData({
      searchGoodsList: this.data.searchGoodsList
    });
  },
  resetfilter: function () {
    this.addactive(this.data.searchGoodsList);
    this.setData({
      startprice: '',
      endprice: '',
      searchGoodsList: this.data.searchGoodsList
    })
  },
  filterlabel: function() {
    shihan.sendRequest(config.search, 'GET', {
        page: 1,
        kw: that.data.searchKeyword
      }, {})
      .then(function(response) {
        if (response.data.data.sh_products.length != 0) {
          that.addactive(response.data.data)
          that.setData({
            searchBrandList: response.data.data.sh_seller,
            searchGoodsList: response.data.data
          });
        }
      }, function(error) {
        console.log(error);
      });
  },
  filterconfirm: function(a, b, c, f, g) {
    shihan.sendRequest(config.search, 'GET', {
        brand_ids: a || '',
        cids: b || '',
        promotion_type: that.data.promotion_type,
        attributes: c || '',
        page: that.data.start,
        page_size: that.data.count,
        start_price: f || '',
        end_price: g || '',
        sort: that.data.sort,
        kw: that.data.searchKeyword
      }, {})
      .then(function(response) {
        if (response.data.data.sh_products.length > 0) {
          for (var i = 0; i < response.data.data.sh_products.length; i++) {
            if (response.data.data.sh_products[i].sh_label.sh_location) {
              var pos = response.data.data.sh_products[i].sh_label
              pos['posa'] = pos.sh_location.split('_')[0];
              pos['posb'] = pos.sh_location.split('_')[1];
            }
          }
          that.setData({
            showLoading: false,
            searchGoods: that.data.searchGoods.concat(response.data.data.sh_products),
            searchResultShow: true
          });
        } else {
          that.setData({
            showLoading: false,
            prohasMore: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  goodsloadMoreData: function () {
    this.setData({
      start: that.data.start + 1,
    })
    this.filterconfirm(this.data.brandids, this.data.cids, this.data.attributes, this.data.startprice, this.data.endprice)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  }
})